package com.example.siyun.controller.filecontroller;

import cn.hutool.http.HttpRequest;
import com.example.siyun.fastdfs.FastDFSClient;
import com.example.siyun.util.FastDFSUtilssp;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@RestController
public class UploadspController {
//    @GetMapping("/index")
//    public String index() {
//        return "upload";
//    }
    @GetMapping("/intermediate/getprocess")
    public String getProcess(HttpServletRequest httpServletRequest) {
        Object percent =  httpServletRequest.getSession().getAttribute("process");
        return String.valueOf(percent);
    }
    /**
     * 上传视频的接口
     * @ruturn 返回上传视频后的数据
     */
    @PostMapping("/sp/upload") //new annotation since 4.3
    public Map<String,String> fileUpload(MultipartFile file,
                                         RedirectAttributes redirectAttributes,HttpSession session,HttpServletRequest request) {
        String path=null;
        System.out.println(file);
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "选个文件啊！");
//            return "redirect:index";
        }
        try {
            // 就用byte数组传输吧
            byte[] file_buff = null;
            InputStream inputStream=file.getInputStream();
            if(inputStream!=null){
                int len1 = inputStream.available();
                file_buff = new byte[len1];
                inputStream.read(file_buff);
            }
            inputStream.close();
            String[] results= FastDFSUtilssp.upload(file_buff);

            //拼接图片访问地址
            path = FastDFSClient.getUrl()+results[0]+ "/"+results[1];
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
            redirectAttributes.addFlashAttribute("path",
                    path);
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println(111111111);
        System.out.println(path);
//        session.setAttribute("spurl",path);
        Map aa=new HashMap();
        aa.put("code","0");
        aa.put("src",path);

        return aa;
//        return "redirect:/index";
    }
}
